package 简单.最长回文串;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liugongding
 * @description:
 * @date 2024/8/31 9:40 PM
 */
public class 最长回文串 {
        public static int longestPalindrome(String s) {
                Map<Character, Integer> map = new HashMap<>();
                int oushu = 0;
                int jishu = 0;
                for (int i = 0; i <s.length(); ++i) {
                    char c = s.charAt(i);
                    map.put(c, map.getOrDefault(c,0) + 1);
                }
                int size = map.size();
                if (size == 1) {
                    return s.length();
                }
                boolean flag = false;
                for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                    Integer value = entry.getValue();
                    if (value % 2 == 0) {
                        oushu += value;
                    } else {
                        jishu += value - 1;
                        flag = true;
                    }
                }
                return flag == true ? oushu+jishu+1 : oushu+jishu;
            }


    public static int longestPalindrome2(String s) {
        // 统计各字符数量
        HashMap<Character, Integer> counter = new HashMap<>();
        for (int i = 0; i < s.length(); i++)
            counter.merge(s.charAt(i), 1, (a, b) -> a + b);
        // 统计构造回文串的最大长度
        int res = 0, odd = 0;
        for (Map.Entry<Character, Integer> kv : counter.entrySet()) {
            // 将当前字符出现次数向下取偶数，并计入 res
            int count = kv.getValue();
            int rem = count % 2;
            res += count - rem;
            // 若当前字符出现次数为奇数，则将 odd 置 1
            if (rem == 1) odd = 1;
        }
        return res + odd;
    }
    public static void main(String[] args) {
        System.out.println(longestPalindrome("adam"));

    }
    }
